package com.doudou.oauth.provider;

import com.doudou.oauth.service.MyUserDetailsService;
import com.doudou.oauth.token.SmsCodeAuthenticationToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @Author: 傻男人
 * @Date: 2020/5/22 10:43
 * @Version: 1.0
 * @Description: 短信身份验证
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private MyUserDetailsService userDetailsService;

    /**
     * 认证的逻辑
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken smsCodeAuthenticationToken = (SmsCodeAuthenticationToken) authentication;
        //获取用户的信息
        UserDetails userDetails = userDetailsService.loadUserByPhone((String) smsCodeAuthenticationToken.getPrincipal());
        //重新封装认证的信息
        SmsCodeAuthenticationToken smsCodeAuthenticationResult = new SmsCodeAuthenticationToken(userDetails,userDetails.getAuthorities());
        //将之前的认证信息copy到认证信息中
        smsCodeAuthenticationResult.setDetails(smsCodeAuthenticationToken.getDetails());
        return smsCodeAuthenticationResult;
    }

    /**
     * 支持的认证
     * @param authentication
     * @return
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public MyUserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(MyUserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}

